package com.cdp.web.controller.system;

import com.alipay.api.domain.AbilityResourceBizMark;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysNtroduce;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.system.dto.NtroduceDTO;
import com.cdp.system.service.SysNtroduceService;
import com.cdp.system.vo.SysNtroduceVO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping
public class NtroduceController {

    @Autowired
    private SysNtroduceService sysNtroduceService;

    @PostMapping("/savaNtroduce")
    public AjaxResult savaNtroduce(@RequestBody NtroduceDTO ntroduceDTO) {
        // 查询表中是否已有记录
        int count = sysNtroduceService.count();

        if (count > 0) {
            // 已存在记录，拒绝保存，返回错误
            return AjaxResult.error("平台介绍信息已存在，只允许保存一条记录");
        }

        SysNtroduce entity = new SysNtroduce();


        entity.setPlatformIntro(ntroduceDTO.getPlatformIntro());
        entity.setPhotoPath(ntroduceDTO.getPhotoPath());
        // 设置系统字段
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(LocalDateTime.now());

        entity.setDeleteTime(0);
        entity.setVersion(0);

        boolean success = sysNtroduceService.save(entity);
        if (success) {
            return AjaxResult.success("保存成功");
        } else {
            return AjaxResult.error("保存失败");
        }
    }

/*
    @PostMapping("/savaNtroduce")
    public AjaxResult savaNtroduce(@RequestBody NtroduceDTO ntroduceDTO) {
        SysNtroduce entity = new SysNtroduce();

        entity.setContactName(ntroduceDTO.getContactName());
        entity.setPhoneNumber(ntroduceDTO.getPhoneNumber());
        entity.setPlatformIntro(ntroduceDTO.getPlatformIntro());
        entity.setPhotoPath(ntroduceDTO.getPhotoPath());
        // 设置系统字段
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setDeleteTime(0);
        entity.setVersion(0);

        boolean success = sysNtroduceService.save(entity);
        if (success) {
            return AjaxResult.success("保存成功");
        } else {
            return AjaxResult.error("保存失败");
        }
    }
*/


    @GetMapping("/getNtroduce")
    public AjaxResult getIntroduce() {
        // 查询唯一记录，不抛异常
        SysNtroduce entity = sysNtroduceService.getOne(null, false);

        if (entity == null) {
            return AjaxResult.error("平台介绍信息不存在");
        }
        // 如需转换为 VO 对象，可在这里做
        SysNtroduceVO vo = new SysNtroduceVO();
        BeanUtils.copyProperties(entity, vo);
        return AjaxResult.success(vo); // 如果无需转换可直接返回 entity
    }


    @PostMapping("/updateNtroduce")
    public AjaxResult updateNtroduce(@Validated @RequestBody NtroduceDTO ntroduceDTO) {
        Integer id = 1;

        // 查询是否存在
        SysNtroduce existing = sysNtroduceService.getById(id);

        // 构建或修改实体
        SysNtroduce entity = existing != null ? existing : new SysNtroduce();
        entity.setId(id);

        if (ntroduceDTO.getMail() != null) {
            entity.setMail(ntroduceDTO.getMail());
        }
        if (ntroduceDTO.getPlatformIntro() != null) {
            entity.setPlatformIntro(ntroduceDTO.getPlatformIntro());
        }
        if (ntroduceDTO.getPhotoPath() != null) {
            entity.setPhotoPath(ntroduceDTO.getPhotoPath());
        }

        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(LocalDateTime.now());

        if (existing == null) {
            entity.setCreateBy(SecurityUtils.getUsername());
            entity.setCreateTime(LocalDateTime.now());
        }

        boolean success = sysNtroduceService.saveOrUpdate(entity);

        return success
                ? AjaxResult.success(existing == null ? "新增成功" : "更新成功")
                : AjaxResult.error("保存失败");
    }


    /**
     * 根据地址解析json
     */


    @PostMapping("analysisJsonFileByUrl")
    private AjaxResult analysisJsonFileByUrl(@RequestBody NtroduceDTO ntroduceDTO) {
        String jsonFilePath = ntroduceDTO.getJsonFileUrl();  // 这是本地文件路径
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 读取文件内容为字符串
            String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFilePath)), StandardCharsets.UTF_8);

            // 解析为 List<List<String>>
            List<List<String>> data = objectMapper.readValue(jsonContent, new TypeReference<List<List<String>>>() {});

            return AjaxResult.success(data);
        } catch (IOException e) {
            return AjaxResult.error("文件读取或 JSON 解析失败：" + e.getMessage());
        }
    }


    /**
     * 解析excek文件
     * @param file
     * @return
     */

//    @PostMapping("analysisExcelFile")
//    private AjaxResult analysisExcelFile(@RequestParam("file") MultipartFile file) {
//        List<List<String>> data = new ArrayList<>();
//
//        try (InputStream inputStream = file.getInputStream()) {
//            Workbook workbook = WorkbookFactory.create(inputStream);
//            Sheet sheet = workbook.getSheetAt(0);  // 只读取第一个工作表
//
//            for (Row row : sheet) {
//                List<String> rowData = new ArrayList<>();
//                for (Cell cell : row) {
//                    cell.setCellType(CellType.STRING);  // 统一处理为字符串类型
//                    rowData.add(cell.getStringCellValue());
//                }
//                data.add(rowData);
//            }
//
//            return AjaxResult.success(data);
//        } catch (IOException e) {
//            return AjaxResult.error("Excel 解析失败：" + e.getMessage());
//        }
//    }


    @PostMapping("analysisExcelFile")
    private AjaxResult analysisExcelFile(@RequestParam("file") MultipartFile file) {
        List<List<String>> data = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

            for (Row row : sheet) {  //Row行
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) { //Cell列
                    String cellValue = parseCell(cell);
                    rowData.add(cellValue);
                }
                data.add(rowData);
            }

            return AjaxResult.success(data);
        } catch (IOException e) {
            return AjaxResult.error("Excel 解析失败：" + e.getMessage());
        }
    }

    private String parseCell(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    // 如果是日期
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
                } else {
                    // 是数字，保留原始值（可加小数位控制）
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                // 公式处理：先尝试用字符串结果
                try {
                    return cell.getStringCellValue();
                } catch (IllegalStateException e) {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BLANK:
                return "";
            default:
                return "未知类型";
        }
    }



}
